package cn.edu.sjtu.se.dslab.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import cn.edu.sjtu.se.dslab.component.data.UploadFile;
import cn.edu.sjtu.se.dslab.dao.IBaseDao;
import cn.edu.sjtu.se.dslab.dao.IUploadFileDao;
import cn.edu.sjtu.se.dslab.util.Const;
import cn.edu.sjtu.se.dslab.util.MD5;
@Repository("uploadFileDao")
public class UploadFileDaoImpl implements IUploadFileDao {
	private static final String URI = "uri";

	@Resource(name = "baseDao")
	private IBaseDao<UploadFile> baseDao;
	@Override
	public void save(UploadFile file) {
		// TODO Auto-generated method stub
		String temp = 
				"UploadFile"
				+  System.currentTimeMillis();
		MD5 md5 = new MD5();
		String uri = md5.getMD5ofStr(temp).substring(0, 8);
		while (!checkUri(Const.URI_UPLOAD_FILE + ":" +uri)) {
			temp = "UploadFile"
					+  System.currentTimeMillis();
			uri = md5.getMD5ofStr(temp).substring(0, 8);
		}
		file.setUri(Const.URI_UPLOAD_FILE + ":" +uri);
		baseDao.save(file);
	}

	@Override
	public List<UploadFile> queryByName(String name) {
		// TODO Auto-generated method stub
		StringBuffer hql = new StringBuffer();
		// 拼接sql语句
		hql.append("from UploadFile a where ");
		hql.append(" a.name like '%");
		hql.append( name+ "%'");
		return baseDao.query(hql.toString());
	}

	@Override
	public boolean checkUri(String uri) {
		// TODO Auto-generated method stub
		UploadFile file = queryByUri(uri);
		if (file != null) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public UploadFile queryByUri(String uri) {
		// TODO Auto-generated method stub
		StringBuffer hql = new StringBuffer();
		// 拼接sql语句
		hql.append("from UploadFile where ");
		hql.append(URI + "=");
		hql.append("'" + uri + "'");
		return baseDao.queryObject(hql.toString());
	}

}
